package com.siyoumi.app.modules.app_ess.admin;

import com.siyoumi.app.entity.EssClass;
import com.siyoumi.app.entity.EssModule;
import com.siyoumi.app.entity.EssTest;
import com.siyoumi.app.modules.app_ess.service.SvcEssClass;
import com.siyoumi.app.modules.app_ess.service.SvcEssModule;
import com.siyoumi.app.modules.app_ess.service.SvcEssTest;
import com.siyoumi.app.modules.app_ess.vo.VaEssClass;
import com.siyoumi.app.modules.app_ess.vo.VaEssModule;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/app_ess/app_ess__module__edit")
public class app_ess__module__edit
        extends AdminApiController {

    @GetMapping()
    public XReturn index() {
        setPageTitle("场景-编辑");

        Map<String, Object> data = new HashMap<>();
        data.put("emod_order", 0);
        if (isAdminEdit()) {
            EssModule entity = SvcEssModule.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        return getR();
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public XReturn save(@Validated() VaEssModule vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        if (XStr.hasAnyText(vo.getEmod_test_id())) {
            EssTest entityTest = SvcEssTest.getApp().getEntity(vo.getEmod_test_id());
            if (entityTest == null) {
                result.addError(XValidator.getErr("emod_test_id", "评价ID不存在"));
            }
        }
        XValidator.getResult(result);
        //
        vo.setEmod_acc_id(getAccId());
        //
        InputData inputData = InputData.fromRequest();
        return SvcEssModule.getBean().edit(inputData, vo);
    }
}